import { FormActionType } from '../types/index';
import { unref } from 'vue';

interface UseFormActionContext {
  emit: any;
  formProps: any;
  formModel: Recordable;
  formRef: any;
  defaultFormModel: Recordable;
}

export default ({
  emit,
  formRef,
  formProps,
  formModel,
  defaultFormModel,
}: UseFormActionContext): FormActionType => {
  // 验证
  const validate = async () => {
    return unref(formRef)?.validate();
  };

  // 获取表单值
  const getFieldsValue = () => {
    return formModel;
  };

  // 清空校验
  const clearValidate = async () => {
    // @ts-ignore
    await unref(formRef)?.restoreValidation();
  };

  // 提交
  const submit = async (e?: Event): Promise<void> => {
    e && e.preventDefault();
    const formEl = unref(formRef);
    if (!formEl) return;
    try {
      await validate();
      emit('onFinish', formModel);
    } catch (error) {}
  };

  // 重置
  const resetFields = async (): Promise<void> => {
    const formEl = unref(formRef);
    if (!formEl) return;
    Object.keys(formModel).forEach((key) => {
      formModel[key] = defaultFormModel[key] || null;
    });
    await clearValidate();
    emit('onReset', formModel);
    emit('onFinish', formModel);
  };

  //设置表单字段值
  const setFieldsValue = async (values: Recordable): Promise<void> => {
    const fields = formProps.columns?.map((item) => item.field).filter(Boolean);

    Object.keys(values).forEach((key) => {
      const value = values[key];
      if (fields.includes(key)) {
        formModel[key] = value;
      }
    });
  };

  return {
    getFieldsValue,
    clearValidate,
    resetFields,
    setFieldsValue,
    validate,
    submit,
  };
};
